package com.mrzhou.core.tool.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class JacksonUtil {

    private static final ObjectMapper objectMapper = getObjectMapper();

    public static synchronized ObjectMapper getObjectMapper() {
        try {
            ObjectMapper om = SpringUtil.getBeanIgnoreNull(ObjectMapper.class);
            if (null == om) {
                om = new ObjectMapper();
                om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            }

            return om;
        } catch (Exception e) {
            log.warn("没有在项目中找到ObjectMapper的Bean, 使用初始话的Bean");
            return new ObjectMapper();
        }
    }

    public static String toJsonString(Object obj) {
        if(null == obj) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static <T> T parseObject(String json, Class<T> clazz) {
        if(!StringUtils.isNotBlank(json)) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
            throw new IllegalArgumentException(e);
        }
    }

    public static <T> T parseObject(String json, TypeReference<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            log.error(e.getLocalizedMessage());
            throw new IllegalArgumentException(e);
        }
    }

}
